from django.shortcuts import render
from rest_framework import generics, mixins, filters, viewsets
from rest_framework.pagination import PageNumberPagination
from rest_framework.authentication import TokenAuthentication
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.throttling import UserRateThrottle, AnonRateThrottle
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from .filters import GoodsFilter
from .serializers import GoodsSerializer, GoodsCategorySerializer, \
    BannerSerializer, IndexCategorySerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Goods, GoodsCategory, Banner


class StandardResultsSetPagination(PageNumberPagination):
    """
    标准分页
    """
    page_size = 10
    page_size_query_param = 'page_size'
    page_number_query_param = 'page'
    max_page_size = 100


class GoodsListViewSet(CacheResponseMixin, mixins.ListModelMixin,mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """Test API View"""
    # 设置请求限制次数
    throttle_classes = (UserRateThrottle, AnonRateThrottle)
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
    pagination_class = StandardResultsSetPagination
    # authentication_classes = [TokenAuthentication]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_class = GoodsFilter
    search_fields = ['name', 'goods_brief', 'goods_desc']
    ordering_fields = ['sold_num', 'shop_price']
    # def get_queryset(self):
    #     return Goods.objects.filter(shop_price__gt=100)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.click_num += 1
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


class GoodsCategoryListViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    List:
        分类列表
    """
    queryset = GoodsCategory.objects.filter(category_type=1)
    serializer_class = GoodsCategorySerializer
    # filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    # ordering_fields = ['sold_num', 'add_time']
    # def get_queryset(self):
    #     return Goods.objects.filter(shop_price__gt=100)


# class GoodsListView(generics.ListAPIView):
#     """Test API View"""
#     queryset = Goods.objects.all()
#     serializer_class = GoodsSerializer
#     pagination_class = StandardResultsSetPagination


class BannerViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    queryset = Banner.objects.all().order_by('index')
    serializer_class = BannerSerializer


class IndexCategoryViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
    queryset = GoodsCategory.objects.filter(is_tab=True)
    serializer_class = IndexCategorySerializer
